package com.apobates.jforum2.troll.accounts.biz.impl;

import com.apobates.jforum2.troll.accounts.biz.RegisteInviteCodeService;
import com.apobates.jforum2.troll.accounts.biz.dao.RegisteInviteCodeDao;
import com.apobates.jforum2.troll.accounts.entity.RegisteInviteCode;
import com.apobates.jforum2.troll.utils.core.Commons;
import com.apobates.jforum2.troll.utils.persistence.Page;
import com.apobates.jforum2.troll.utils.persistence.Pageable;
import java.util.Optional;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
 *
 * @author xiaofanku
 * @since 20200515
 */
@Service
public class RegisteInviteCodeServiceImpl implements RegisteInviteCodeService{
    @Autowired
    private RegisteInviteCodeDao registeInviteCodeDao;
    private final static Logger logger = LoggerFactory.getLogger(RegisteInviteCodeServiceImpl.class);
    
    @Override
    public Page<RegisteInviteCode> get(Pageable pageable) {
        return registeInviteCodeDao.findAll(pageable);
    }
    
    @Override
    public Optional<RegisteInviteCode> get(long id) {
        return registeInviteCodeDao.findOne(id);
    }
    
    @Override
    public Optional<RegisteInviteCode> get(String code) {
        if (!Commons.isNotBlank(code)) {
            return Optional.empty();
        }
        return registeInviteCodeDao.findOne(code);
    }
    
    @Override
    public Optional<Boolean> remove(long id)throws IllegalArgumentException,IllegalStateException {
        RegisteInviteCode ric = get(id).orElseThrow(()->new IllegalArgumentException("注册邀请码不存在"));
        if (ric.isActive()) {
            throw new IllegalStateException("邀请码已经激活不可以删除");
        }
        ric.setStatus(false);
        return registeInviteCodeDao.edit(ric);
    }
    
    @Override
    public Optional<Boolean> activeCode(long id, long memberId, String memberNames) {
        return registeInviteCodeDao.active(id, memberId, memberNames);
    }
    
    @Override
    public long create(String leader, String code) {
        return create(new RegisteInviteCode(leader, code));
    }
    private long create(RegisteInviteCode inviteCode) {
        try {
            registeInviteCodeDao.save(inviteCode);
            if (inviteCode.getId() > 0) {
                return inviteCode.getId();
            }
        } catch (Exception e) {
            if(logger.isDebugEnabled()){
                logger.debug("注册邀请码创建失败", e);
            }
        }
        return 0L;
    }
}